package ${project.packageName}.${project.dataCenterType}.client.jedis;


import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import com.alibaba.fastjson.JSONObject;
import ${project.packageName}.${project.dataCenterType}.client.jodis.JedisResourcePool;


/**
 * jedis操作类
 * 
 * @author yangjian
 */
@Component
public class JedisActionClient {

    @Autowired
    private JedisResourcePool jedisPool;

    private final static Logger LOG = LoggerFactory.getLogger(JedisActionClient.class);

    /**
     * 根据key返回Obj对象(在缓存里面取出)
     * 
     * @return Object
     * @throws IOException
     */
    public Object getObject(String key) {

        // 获取缓存连接
        Jedis jedis = jedisPool.getResource();
        // 获取缓存数据
        byte[] data = jedis.get(key.getBytes());
        LOG.info("data..." + JSONObject.toJSONString(data));
        Object obj = SerializableHelper.deserialize(data);
        jedis.close();
        return obj;

    }

    /**
     * 批量插入缓存信息
     */
    public void getBatchObj(List<Map<String, String>> list, Integer time) {

        // 获取缓存对象
        try {
            Jedis jedis = jedisPool.getResource();
            Pipeline p = jedis.pipelined();

            int index = 0;
            for (Map<String, String> pram : list) {
                p.set(pram.get("$_key_$").getBytes(), SerializableHelper.serialize(pram));
                if (time != null && !"".equals(time)) {
                    p.expire(pram.get("$_key_$").getBytes(), time);
                }
                if (++index % 10000 == 0) {
                    p.sync();
                }
            }

            p.sync();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据传入的参数信息,组合新的key,并从数据库中得到该条数据,最后刷数据到缓存中 24小时 = 86400
     * 
     * @throws IOException
     */
    public void createObject(final String key, final Object obj, final Long time) {
        // 获取缓存对象
        Jedis jedis = jedisPool.getResource();
        jedis.set(key.getBytes(), SerializableHelper.serialize(obj));

        // 判断失效时间是否存在
        if (time != null && !"".equals(time)) {
            // 设置时间信息失效
            jedis.expire(key, Integer.parseInt(time.toString()));
        }
        // 关闭流
        jedis.close();
    }

    /**
     * 批量从缓存中取出数据信息
     */
    public Set<String> getKeysObj(final String key) {

        // 获取缓存对象
        Jedis jedis = jedisPool.getResource();

        // 根据key删除数据值信息
        Set<String> data = jedis.keys(key);

        // 关闭流
        jedis.close();
        return data;
    }

}
